package com.gary.security.repository.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;

import com.gary.security.AuthenticationHelper;
import com.gary.security.entity.Resc;
import com.gary.security.entity.Role;
import com.gary.security.model.resource.Resource;

public class RescCallback implements HibernateCallback{
	 /** * 角色前缀. */
    private String rolePrefix = "";

    /**
     * 构造方法.
     *
     * @param rolePrefix 角色前缀
     */
    public RescCallback(String rolePrefix) {
        this.rolePrefix = rolePrefix;
    }

    /**
     * 保存资源.
     *
     * @param session Session
     * @return 资源
     */
    @SuppressWarnings("unchecked")
	public Object doInHibernate(Session session) {
        List<Resc> rescs = session.createCriteria(Resc.class).list();

        List<Resource> authResources = new ArrayList<Resource>();

        for (Resc resc : rescs) {
            GrantedAuthority[] arrayAuths = AuthenticationHelper
                .convertToGrantedAuthority(getAuthsByResource(resc));
            authResources.add(new Resource(resc.getResString(),
                    resc.getResType(), arrayAuths));
        }

        return authResources;
    }

    /**
     * 使用资源获得权限.
     *
     * @param resc Resc
     * @return 权限列表
     */
    private List<GrantedAuthorityImpl> getAuthsByResource(Resc resc) {
        List<GrantedAuthorityImpl> list = new ArrayList<GrantedAuthorityImpl>();

        for (Role role : resc.getRoles()) {
            String roleName = rolePrefix + role.getName();
            GrantedAuthorityImpl authority = new GrantedAuthorityImpl(roleName);
            list.add(authority);
        }

        return list;
    }
}
